<?php


namespace App\Services;


use App\Models\User;
use App\Models\UserSecret;
use App\Utils\Code;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use phpDocumentor\Reflection\Types\Integer;

class BaseService
{
    /**
     * 用户信息
     * @var null|User
     */
    protected static $user = null;

    /**
     * 是否管理员
     * @var bool
     */
    protected static $admin = false;

    /**
     * 初始化方法
     * BaseService constructor.
     */
    public function __construct()
    {
        if (\Auth::id()) {
            // 设置用户信息
            $this::$user = \Auth::user();
            // 验证是否管理
            $this::$admin = $this::$user && $this::$user->is_admin == 1;
        }
    }

    /**
     * 辅助数据
     * @param array $params
     * @return array
     */
    public function assist(array $params = []) {
        $data = [];
        return $data;
    }

    /**
     * 时间查询条件
     * @param Model|Builder $model
     * @param $field
     * @param array $params
     * @return Model|Builder
     */
    // protected function whereDate($model, $field, array $params = []){
    //     $s_time = isset($params['s_time']) && $params['s_time'] ? $params['s_time'] : null;
    //     $e_time = isset($params['e_time']) && $params['e_time'] ? $params['e_time'] : null;
    //     if ($s_time){
    //         $model = $model->where($field, '>=', $s_time);
    //     }
    //     if ($e_time){
    //         $model = $model->where($field, '<=', $e_time);
    //     }
    //     return $model;
    // }

    /**
     * 通知轮循
     * @param array $params
     * @return array
     */
    public function newNotice(array $params = []) {
        if (\Auth::id() && $cookie = request()->header('x-requested-cookie')) {
            if (UserSecret::where('user_id', \Auth::id())->where('cookie', $cookie)->doesntExist()) {
                throw new \Exception('该用户已在其他终端登录', Code::EXPIRED);
            }
        }
        $data = [];
        if (isset($params['qr_code']) && $params['qr_code']) {
            if ($secretInfo = UserSecret::where('session', $params['qr_code'])->first()) {
                UserSecret::where('session', $params['qr_code'])->update(['session' => '']);
                $data['cookie'] = $secretInfo->cookie;
                $data['authorization'] = 'Bearer ' . $secretInfo->current_token;
            } else {
                $data['cookie'] = null;
                $data['authorization'] = null;
            }
        }
        return $data;
    }
}
